package kdt

import (
	"encoding/json"
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"net/http"
)

func ProductQueryAll(w http.ResponseWriter, r *http.Request) {
	crossDomain(w)
	var backData struct {
		State string
		Ps    []Product
	}
	var e error
	backData.Ps, e = getAllProducts()
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	backData.State = "OK"
	ReturnData(w, backData)
}
func ProductQuery(w http.ResponseWriter, r *http.Request) {
	crossDomain(w)
	msg := Msg{} //State:ProductId
	b, e := ioutil.ReadAll(r.Body)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	e = json.Unmarshal(b, &msg)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	var backData struct {
		State string
		P     Product
	}
	backData.P, e = getProductById(msg.State)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	backData.State = "OK"
	ReturnData(w, backData)
}
func getProductById(pid string) (Product, error) {
	p := Product{}
	s, e := mgo.Dial(MongoDBServer)
	if e != nil {
		fmt.Println(e)
		return p, e
	}
	defer s.Close()
	e = s.DB("kdt").C("products").Find(bson.M{"productid": pid}).One(&p)
	if e != nil {
		fmt.Println(e)
		return p, e
	}
	return p, nil
}
func getAllProducts() ([]Product, error) {
	s, e := mgo.Dial(MongoDBServer)
	if e != nil {
		fmt.Println(e)
		return nil, e
	}
	defer s.Close()
	ps := []Product{}
	e = s.DB("kdt").C("products").Find(nil).All(&ps)
	return ps, e
}
func addProduct(p Product) error {
	s, e := mgo.Dial(MongoDBServer)
	if e != nil {
		fmt.Println(e)
		return e
	}
	defer s.Close()
	e = s.DB("kdt").C("products").Insert(p)
	if e != nil {
		return e
	}
	return nil
}
